package com.oasystem.dao.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.oasystem.domain.Operator;
import com.oasystem.domain.OperatorPermission;
import com.oasystem.domain.Permission;

public class PermissionDAO {

	private JdbcTemplate jdbcTemplate;

	public List<Permission> getAll() {
		return jdbcTemplate
				.query("select id,permissionID,description from permission order by permissionID asc",
						new RowMapper<Permission>() {

							public Permission mapRow(ResultSet rs, int arg1)
									throws SQLException {
								Permission permission = new Permission();
								permission.setDescription(rs
										.getString("description"));
								permission.setPermissionID(rs
										.getInt("permissionID"));
								permission.setId(rs.getInt("id"));
								return permission;
							}

						});
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void insertUserPermission(final Operator operator) {
		final int batchSize = operator.getPermissions().size();
		jdbcTemplate
				.batchUpdate(
						"insert into operatorpermission(permissionId,operatorID) values(?,?)",
						new BatchPreparedStatementSetter() {

							public void setValues(PreparedStatement ps,
									int index) throws SQLException {
								ps.setInt(1,
										operator.getPermissions().get(index)
												.getPermissionID());
								ps.setInt(2, operator.getId());
							}

							public int getBatchSize() {
								return batchSize;
							}
						});
	}

	public void loadByOperatorID(Operator operator) {
		List<OperatorPermission> list = jdbcTemplate.query(
				"select * from operatorpermission where operatorID=?",
				new Object[] { operator.getId() },
				new RowMapper<OperatorPermission>() {

					public OperatorPermission mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						OperatorPermission op = new OperatorPermission();
						op.setOperatorID(rs.getInt("operatorID"));
						op.setPermissionID(rs.getInt("permissionID"));
						return op;
					}
				});
		
		for(OperatorPermission op : list)
		{
			Permission p = new Permission();
			p.setPermissionID(op.getPermissionID());
			operator.getPermissions().add(p);
		}
	}

	public void deleteUserPermission(Operator operator) {
		jdbcTemplate.update("delete from operatorpermission where operatorID=?",new Object[]{operator.getId()});
	}

}
